package com.pig4cloud.pig.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.admin.api.dto.UserDTO;
import com.pig4cloud.pig.admin.api.entity.*;
import com.pig4cloud.pig.admin.mapper.BsAccountManageMapper;
import com.pig4cloud.pig.admin.service.BsAccountManageService;
import com.pig4cloud.pig.admin.service.BsVipManageService;
import com.pig4cloud.pig.admin.service.BusOperateDetailService;
import com.pig4cloud.pig.admin.service.SysUserService;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import okhttp3.*;

import java.io.IOException;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 账户
 *
 * @author pig
 * @date 2025-04-03 17:43:34
 */
@Service
@AllArgsConstructor
public class BsAccountManageServiceImpl extends ServiceImpl<BsAccountManageMapper, BsAccountManageEntity> implements BsAccountManageService {
	private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

	private final SysUserService userService;

	private final BsVipManageService bsVipManageService;

	private final BusOperateDetailService busOperateDetailService;

	private static String psd = "123456";

	/**
	 * 注册账户 绑定sysuser
	 *
	 * @param bsAccountManage
	 * @return
	 */
	@Override
	public boolean saveAccount(BsAccountManageEntity bsAccountManage) {
		// 创建人
		bsAccountManage.setCreator(SecurityUtils.getUser().getName());
		bsAccountManage.setBuyTime(LocalDateTime.now());
		//创建时间
		bsAccountManage.setCreateTime(LocalDateTime.now());
		//admin账号赋值激活
		bsAccountManage.setDeleteFlag(0);
		//航司 在页面保存
		baseMapper.insert(bsAccountManage);
		//添加时注册用户
//		UserDTO sysUser = new UserDTO();
//		sysUser.setName(bsAccountManage.getAccountName());
//		sysUser.setNickname(bsAccountManage.getAccountName());
//		//		绑定账户名为登录名称
//		sysUser.setUsername(bsAccountManage.getAccountName());
//		sysUser.setDelFlag(CommonConstants.STATUS_NORMAL);
//		sysUser.setCreateBy(bsAccountManage.getAccountName());
//		//初始化账户密码为123456
//		sysUser.setPassword(psd);
//		userService.saveUser(sysUser);
		return true;
	}

	@Override
	public boolean initBalace(BsAccountManageEntity bsAccountManage) {

		// 逻辑在测试

		return false;
	}

	/**
	 * 赠送积分
	 *
	 * @param bsGiftEntity
	 * @return
	 */
	@Override
	public boolean giftBalace(BsGiftEntity bsGiftEntity) {
		// 逻辑在测试
		try {
			return transferPoints(bsGiftEntity.getAccountId(), bsGiftEntity.getReciveAccountId(), new BigDecimal(bsGiftEntity.getBalance()));
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 执行积分转移操作
	 *
	 * @param accountId 账户 ID
	 * @param vipId     VIP ID
	 * @param points    转移的积分数
	 * @throws Exception 如果操作失败
	 */
	public boolean transferPoints(long accountId, long vipId, BigDecimal points) {
		//明细表
		BusOperateDetailEntity busOperateDetailEntity = new BusOperateDetailEntity();
		busOperateDetailEntity.setCreator(SecurityUtils.getUser().getName());
		busOperateDetailEntity.setCreateTime(LocalDateTime.now());
		busOperateDetailEntity.setOperatorId(accountId);
		busOperateDetailEntity.setRecipientId(vipId);
		busOperateDetailEntity.setTotalBalance(String.valueOf(points));
		// 1. 扣除账户积分
		BsAccountManageEntity bsAccountManage = this.getById(accountId);
		if (bsAccountManage == null) {
//			throw new Exception("账户积分不足或账户不存在");
			//插入记录表： 账户不存在  状态失败
			busOperateDetailEntity.setStatus(0);
			busOperateDetailEntity.setProcess(0);	//0:账号 1：vip会员 2：账户扣除 3：vip增加
			busOperateDetailEntity.setMsg("信息--账户："+accountId+"赠送"+points+"积分时，账户："+accountId+"不存在");
			busOperateDetailService.save(busOperateDetailEntity);
			return false;
		}
		boolean deductRows = deductPoints(bsAccountManage, points);
		if (!deductRows) {
			//插入记录表： 后续从记录表再次申请  状态失败
			busOperateDetailEntity.setStatus(0);
			busOperateDetailEntity.setOperator(bsAccountManage.getAccountName());
			busOperateDetailEntity.setProcess(2);
			busOperateDetailEntity.setMsg("信息--账户："+bsAccountManage.getAccountName()+"赠送"+points+"积分时，账户："+bsAccountManage.getAccountName()+"账户积分不足");
			busOperateDetailService.save(busOperateDetailEntity);
			return false;
		}else {
			busOperateDetailEntity.setOperator(bsAccountManage.getAccountName());
		}
		// 2. 增加 VIP 用户积分
		BsVipManageEntity bsVipManage = bsVipManageService.getById(vipId);
		if (bsVipManage == null) {
			//插入记录表： 后续从记录表再次申请  状态失败
			busOperateDetailEntity.setStatus(0);
			busOperateDetailEntity.setProcess(1);
			busOperateDetailEntity.setRecipient(bsVipManage.getUserName());
			busOperateDetailEntity.setMsg("信息--会员："+vipId+"赠送"+points+"积分时，账户："+vipId+"不存在");
			busOperateDetailService.save(busOperateDetailEntity);
			//返还 积分
			addPointsToAccount(bsAccountManage, points);
			return false;
		}
		boolean addRows = addPointsToVip(bsVipManage, points);
		if (addRows) {
			//插入记录表： 后续从记录表再次申请  状态失败
			busOperateDetailEntity.setStatus(1);
			busOperateDetailEntity.setProcess(3);
			busOperateDetailEntity.setRecipient(bsVipManage.getUserName());
			busOperateDetailEntity.setMsg("信息--账户："+bsAccountManage.getAccountName()+"赠送"+bsVipManage.getAccount()+points+"积分成功");
			busOperateDetailService.save(busOperateDetailEntity);

			return true;
		}else {
			//返还 积分
			addPointsToAccount(bsAccountManage, points);
			return false;
		}
	}


	/**
	 * // 2. 增加 VIP 用户积分
	 *
	 * @param bsVipManage
	 * @param points
	 * @return
	 */
	private boolean addPointsToVip(BsVipManageEntity bsVipManage, BigDecimal points) {
		BigDecimal balance = new BigDecimal(bsVipManage.getBalance());
		BigDecimal subBalance = balance.add(points);
		bsVipManage.setBalance(String.valueOf(subBalance));
		return bsVipManageService.updateById(bsVipManage);
	}

	/**
	 * // 1. 扣除账户积分
	 *
	 * @param bsAccountManage
	 * @param points
	 * @return
	 */
	private boolean deductPoints(BsAccountManageEntity bsAccountManage, BigDecimal points) {
		BigDecimal balance = new BigDecimal(bsAccountManage.getTotalBalance());
		BigDecimal subBalance = balance.subtract(points);
		if (subBalance.compareTo(BigDecimal.ZERO) <= 0) {
			//插入记录表： 账户积分不足 状态失败
			return false;
		} else {
			bsAccountManage.setTotalBalance(String.valueOf(subBalance));
			return this.updateById(bsAccountManage);
		}
	}

	/**
	 * // 1. 扣除账户积分
	 *
	 * @param bsAccountManage
	 * @param points
	 * @return
	 */
	private int addPointsToAccount(BsAccountManageEntity bsAccountManage, BigDecimal points) {
		BigDecimal balance = new BigDecimal(bsAccountManage.getTotalBalance());
		BigDecimal subBalance = balance.add(points);
		bsAccountManage.setTotalBalance(String.valueOf(subBalance));
		return baseMapper.updateById(bsAccountManage);
	}



	private static final OkHttpClient client = new OkHttpClient();

	/**
	 * 更新 VIP 用户积分
	 *
	 * @param url    接口 URL
	 * @param vipId  VIP 用户 ID
	 * @param points 更新的积分数
	 * @return 响应结果
	 * @throws Exception 如果请求失败
	 */
	public static String updateVipPoints(String url, int vipId, int points) throws Exception {
		// 创建请求体 JSON 数据
		String jsonBody = String.format("{\"vipId\":%d,\"points\":%d}", vipId, points);

		// 创建请求体
		RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));

		// 创建请求
		Request request = new Request.Builder()
				.url(url)
				.post(body)
				.build();

		// 执行请求并获取响应
		try (Response response = client.newCall(request).execute()) {
			if (!response.isSuccessful()) {
				throw new IOException("HTTP 错误码: " + response.code());
			}
			return response.body().string();
		}
	}

}